package io.renren.modules.goods.controller;

import io.renren.common.utils.R;
import io.renren.modules.goods.entity.GoodsCategoryEntity;
import io.renren.modules.goods.service.GoodsCategoryService;
import io.renren.modules.sys.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * Created by dell on 2021/8/12.
 */
@RestController
@RequestMapping("/goods")
public class GoodsCategoryController {
    @Autowired
    private GoodsCategoryService goodsCategoryService;

    /**
     * 所有种类列表
     * */
    @GetMapping("/category/list")
    public List<GoodsCategoryEntity> list() {
        List<GoodsCategoryEntity> goodsCategoryList = goodsCategoryService.list();
        HashMap<Long, GoodsCategoryEntity> goodsCategoryMap = new HashMap<>(12);
        for (GoodsCategoryEntity g : goodsCategoryList) {
            goodsCategoryMap.put(g.getCategoryId(), g);
        }
        for (GoodsCategoryEntity g : goodsCategoryList) {
            GoodsCategoryEntity parent = goodsCategoryMap.get(g.getParentId());
            if(Objects.nonNull(parent)) {
                g.setParentName(parent.getLabel());
            }
        }
        return goodsCategoryList;
    }

    /**
     *  tree 结构
     * */


    /**
     * 选择种类
     * */
    @GetMapping("/category/select")
    public R select() {
        List<GoodsCategoryEntity> goodsCategoryList = goodsCategoryService.list();
        HashMap<Long, GoodsCategoryEntity> goodsCategoryMap = new HashMap<>(12);
        for (GoodsCategoryEntity g : goodsCategoryList) {
            goodsCategoryMap.put(g.getCategoryId(), g);
        }
        for (GoodsCategoryEntity g : goodsCategoryList) {
            GoodsCategoryEntity parent = goodsCategoryMap.get(g.getParentId());
            if(Objects.nonNull(parent)) {
                g.setParentName(parent.getLabel());
            }
        }
        GoodsCategoryEntity root = new GoodsCategoryEntity();
        root.setCategoryId(0L);
        root.setLabel("一级分类");
        root.setParentId(-1L);
        goodsCategoryList.add(root);

        return R.ok().put("goodsCategoryList", goodsCategoryList);
    }

    /**
     * 保存
     * */
    @PostMapping("/category/save")
    public R save( @RequestBody GoodsCategoryEntity goodsCategory) {
        goodsCategoryService.save(goodsCategory);
        return R.ok();
    }


}
